﻿using Core.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;

namespace Core.DataAccess.Model
{
    public class iToolLogFunctionSaveProvider
    {
        private readonly IDBFactory iDBFactory;
        private readonly Subject<LogFunction> subject;
        private const string tabelName = "[LogFunction]";

        public iToolLogFunctionSaveProvider(IDBFactory iDBFactory)
        {
            this.iDBFactory = iDBFactory;
            this.subject = new Subject<LogFunction>();
            this.subject
                .Buffer(TimeSpan.FromSeconds(2), 100)
                .Where(x => x.Count > 0)
                .Select(list => Observable.FromAsync(() => BatchInsertData(list)))
                .Concat()
                .Subscribe();

        }

        public void InsertItem(LogFunction log)
        {
            this.subject.OnNext(log);
        }

        private Task BatchInsertData(IList<LogFunction> list)
        {
            DataTable table = DataConver.ListToDataTable(tabelName, list);

            //using (var connection = this.iDBFactory.Create(DatabaseType.Logger) as SqlConnection)
            //{
            //    var bulkCopy = new SqlBulkCopy(connection);
            //    bulkCopy.DestinationTableName = tabelName;
            //    bulkCopy.BulkCopyTimeout = 0;
            //    bulkCopy.WriteToServer(table);
            //}

            return Task.CompletedTask;
        }

    }
}
